import { ConfigProvider, Form, Input } from "antd";
import React, { useContext, useEffect, useState } from "react";
import { LowCodeDesignerContext } from "./Provider";
import useDesignerActions from "./useActions";
import { LowCodeContext } from "../core/Provider";
import { findItemById } from "../shared";
import { produce } from "immer"

const DesignerSetter = () => {
  const [form] = Form.useForm();
  const [setterEl, setSetterEl] = useState<any>(null);
  const { updateDesigner } = useDesignerActions();
  const { components, items } = useContext(LowCodeContext);
  const { currentDesigner } = useContext(LowCodeDesignerContext);
  useEffect(() => {

    if (currentDesigner && currentDesigner.type) {
      let XComponent = components[currentDesigner.type];

      if (XComponent) {
        const { Setter } = XComponent
        setSetterEl(Setter ? <Setter /> : null);
      } else {
        setSetterEl(null)
      }

    } else {
      setSetterEl(null);
    }
  }, [currentDesigner]);
  useEffect(() => {
    form.resetFields();
    // if (currentDesigner.props) {
    form.setFieldValue('children', currentDesigner.children);
    form.setFieldsValue(currentDesigner.props);
    // }
  }, [currentDesigner._id]);
  const onValuesChange = () => {
    const { children, ...values } = form.getFieldsValue();
    const props = currentDesigner["props"];

    const nextState = produce(items, draft => {
      const item = findItemById([draft], currentDesigner._id)
      item.props = {
        ...props,
        ...values,
      }
      if (children) {
        item.children = children
      }
    })

    updateDesigner(nextState);
  };
  return (
    <ConfigProvider componentSize="small">
      <Form form={form} onValuesChange={onValuesChange}>
        <Form.Item label="组件">{currentDesigner.type}</Form.Item>
        <Form.Item label="背景颜色" name={['style','backgroundColor']}>
          <Input />
        </Form.Item>
        <Form.Item label="标识" name="$ref">
          <Input />
        </Form.Item>
        {setterEl}
      </Form>
    </ConfigProvider>
  );
};
export default DesignerSetter;
